interface SpeechOptions {
    lang?: string;
    pitch?: number;
    rate?: number;
    volume?: number;
    onStart?: () => void;
    onEnd?: () => void;
    onError?: (error: any) => void;
  }
  
  class SpeechService {
    private static instance: SpeechService;
    private speaking: boolean = false;
    private messageQueue: string[] = [];
  
    private constructor() {
      // 私有构造函数，确保单例模式
    }
  
    public static getInstance(): SpeechService {
      if (!SpeechService.instance) {
        SpeechService.instance = new SpeechService();
      }
      return SpeechService.instance;
    }
  
    public speak(text: string, options: SpeechOptions = {}) {
      // 检查浏览器支持
      if (!('speechSynthesis' in window)) {
        console.error('浏览器不支持语音合成');
        return;
      }
  
      // 将消息添加到队列
      this.messageQueue.push(text);
      
      // 如果当前没有在播放，开始播放
      if (!this.speaking) {
        this.processQueue();
      }
    }
  
    private processQueue() {
      if (this.messageQueue.length === 0) {
        this.speaking = false;
        return;
      }
  
      this.speaking = true;
      const text = this.messageQueue.shift()!;
      const utterance = new SpeechSynthesisUtterance(text);
  
      // 默认配置
      utterance.lang = 'zh-CN';
      utterance.pitch = 1;
      utterance.rate = 1.1;
      utterance.volume = 1;
  
      // 语音结束后处理队列中的下一条消息
      utterance.onend = () => {
        this.processQueue();
      };
  
      utterance.onerror = (error) => {
        console.error('语音合成错误:', error);
        this.processQueue();
      };
  
      window.speechSynthesis.speak(utterance);
    }
  
    public cancel() {
      window.speechSynthesis.cancel();
      this.messageQueue = [];
      this.speaking = false;
    }
  }
  
  // 导出单例实例
  export const speechService = SpeechService.getInstance();